import {EventEmitter} from './events'
import {raf, caf} from './dom'

class Timer extends EventEmitter {
  constructor (options) {
    super()
    this.options = options || {}

    this.gap = +this.options.gap || 1000
    this.isRaf = +this.options.isRaf || false
    this.task = null
    this.dotTime = new Date().getTime()
  }

  start () {
    this.trigger('start', {options: this.options})
    this.stop()
    this._startTimer()
  }

  stop () {
    const duration = this._passedTime()
    if (!this.task) {
      return
    }
    this._clearTimer()
    if (duration > 0) {
      this.trigger('tick', {options: this.options, duration, isStop: true})
    }
    this.trigger('stop', {options: this.options})
  }

  _internalF () {
    const duration = this._passedTime()
    if (duration > 0) {
      this.trigger('tick', {options: this.options, duration, isStop: false})
    }
    this._startTimer()
  }

  _clearTimer () {
    this.task = null
    if (this.isRaf) {
      caf(this.task)
    } else {
      clearTimeout(this.task)
    }
  }

  _startTimer () {
    if (this.isRaf) {
      this.task = raf(() => this._internalF())
    } else {
      this.task = setTimeout(() => this._internalF(), this.gap)
    }
  }

  _passedTime () {
    const now = new Date().getTime()
    const passedTime = now - this.dotTime
    this.dotTime = now
    return passedTime
  }
}

export default Timer
